import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import CategoryView from '../views/CategoryView.vue';
import CartView from '../views/CartView.vue';
import MyView from '../views/MyView.vue';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: {
        title: '首页',
        requireAuth: false,
        showTabBar: true
      }
    },
    {
      path: '/category',
      name: 'category',
      component: CategoryView,
      meta: {
        title: '商品分类',
        requireAuth: false,
        showTabBar: true
      }
    },
    {
      path: '/cart',
      name: 'cart',
      component: CartView,
      meta: {
        title: '购物车',
        requireAuth: false,
        showTabBar: true
      }
    },
    {
      path: '/my',
      name: 'my',
      component: MyView,
      meta: {
        title: '我的',
        requireAuth: true,
        showTabBar: true
      }
    },
    {
      path: '/auth',
      name: 'auth',
      component: () => import('../views/AuthView.vue'),
      meta: {
        title: '认证页',
        requireAuth: false,
        guestOnly: true
      }
    },
    {
      path: '/401',
      name: 'notauth',
      component: () => import('../views/NotAuth.vue'),
      meta: {
        title: "未认证",
        requireAuth: false,
      }
    },
    {
      path: '/403',
      name: 'nopermission',
      component: () => import('../views/NoPermission.vue'),
      meta: {
        title: "权限不足",
        requireAuth: false,
      }
    },
    {
      path: '/404',
      name: 'notfound',
      component: () => import('../views/NotFound.vue'),
      meta: {
        title: "未找到页面",
        requireAuth: false,
      }
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    }
  ],
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  function isAuthenticated() {
    return !!localStorage.getItem('token');
  }

  const auth = isAuthenticated();

  document.title = to.meta.title || '默认标题';

  if (to.matched.some(record => record.meta.requireAuth)) {
    if (!auth) {
      next({
        path: '/401',
        query: { redirect: to.fullPath }
      });
    } else {
      next();
    }
  } else if (to.matched.some(record => record.meta.guestOnly)) {
    if (auth) {
      next({ name: 'home' });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
